package org.basic.sms.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jodd.util.StringUtil;
import lombok.RequiredArgsConstructor;
import org.basic.common.core.exception.ServiceException;
import org.basic.common.core.utils.MapstructUtils;
import org.basic.common.core.utils.StringUtils;
import org.basic.common.mybatis.core.page.PageQuery;
import org.basic.common.mybatis.core.page.TableDataInfo;
import org.basic.sms.config.SmsConfigProperties;
import org.basic.sms.domain.*;
import org.basic.sms.domain.dto.MessageSendDTO;
import org.basic.sms.domain.bo.SysSmsTemplateBo;
import org.basic.sms.domain.dto.SysTemplateChangeStatusDTO;
import org.basic.sms.domain.vo.SysSmsTemplateVo;
import org.basic.sms.enums.ChannelTypeEnums;
import org.basic.sms.mapper.SysSmsChannelMapper;
import org.basic.sms.mapper.SysSmsLogMapper;
import org.basic.sms.mapper.SysSmsTemplateMapper;
import org.basic.sms.mapper.SysSmsTemplateParamMapper;
import org.basic.sms.service.ISysSmsTemplateParamService;
import org.basic.sms.service.ISysSmsTemplateService;
import org.basic.sms.service.MessageService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 邮件模板Service业务层处理
 *
 * @author Shao Hua
 * @date 2023-07-20
 */
@RequiredArgsConstructor
@Service
public class SysSmsTemplateServiceImpl implements ISysSmsTemplateService {

    private final SysSmsTemplateMapper baseMapper;

    private final SysSmsChannelMapper sysSmsChannelMapper;

    private final SmsConfigProperties smsConfigProperties;

    private final SysSmsTemplateParamMapper sysSmsTemplateParamMapper;

    private final ISysSmsTemplateParamService  iSysSmsTemplateParamService;

    private final SysSmsLogMapper sysSmsLogMapper;


    /**
     * 查询邮件模板
     */
    @Override
    public SysSmsTemplateVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询邮件模板列表
     */
    @Override
    public TableDataInfo<SysSmsTemplateVo> queryPageList(SysSmsTemplateBo bo, PageQuery pageQuery) {
//        Page<SysSmsTemplateVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        Page<SysSmsTemplateVo> result = baseMapper.selectListByPage(pageQuery.build(), bo);
        return TableDataInfo.build(result);
    }

    /**
     * 查询邮件模板列表
     */
    @Override
    public List<SysSmsTemplateVo> queryList(SysSmsTemplateBo bo) {
        LambdaQueryWrapper<SysSmsTemplate> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<SysSmsTemplate> buildQueryWrapper(SysSmsTemplateBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<SysSmsTemplate> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getName()), SysSmsTemplate::getName, bo.getName());
        lqw.eq(StringUtils.isNotBlank(bo.getCode()), SysSmsTemplate::getCode, bo.getCode());
        lqw.eq(bo.getType() != null, SysSmsTemplate::getType, bo.getType());
        lqw.eq(StringUtils.isNotBlank(bo.getContent()), SysSmsTemplate::getContent, bo.getContent());
        lqw.eq(bo.getChannelId() != null, SysSmsTemplate::getChannelId, bo.getChannelId());
        lqw.eq(bo.getStatus() != null, SysSmsTemplate::getStatus, bo.getStatus());
        return lqw;
    }

    /**
     * 新增邮件模板
     */
    @Override
    public Boolean insertByBo(SysSmsTemplateBo bo) {
        SysSmsTemplate add = MapstructUtils.convert(bo, SysSmsTemplate.class);
        validEntityBeforeSave(add);
        List<String> paramNames = parseContentParam(bo.getContent());
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
            if(CollectionUtil.isNotEmpty(paramNames)){
                List<SysSmsTemplateParam> smsTemplateParams = paramNames.stream().map(data -> {
                    SysSmsTemplateParam param = new SysSmsTemplateParam();
                    param.setParamName(data);
                    param.setTemplateId(add.getId());
                    return param;
                }).collect(Collectors.toList());
                if(CollectionUtil.isNotEmpty(smsTemplateParams)){
                    sysSmsTemplateParamMapper.insertBatch(smsTemplateParams);
                }
            }
        }
        return flag;
    }

    /**
     * 解析内容中的参数
     * */
    public static List<String> parseContentParam(String content) {
        if(StringUtils.isEmpty(content)){
            return new ArrayList<>();
        }
        String patternString = "\\$\\{([^}]+)}";
        Pattern pattern = Pattern.compile(patternString);
        Matcher matcher = pattern.matcher(content);

        List<String> paramNames = new ArrayList<>();
        while (matcher.find()) {
            String paramName = matcher.group(1);
            paramNames.add(paramName);
        }
        return paramNames;
    }

    /**
     * 修改邮件模板
     */
    @Override
    public Boolean updateByBo(SysSmsTemplateBo bo) {
        SysSmsTemplate update = MapstructUtils.convert(bo, SysSmsTemplate.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(SysSmsTemplate entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除邮件模板
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public void sendMessage(MessageSendDTO dto) {
        Long templateId = dto.getTemplateId();

        SysSmsTemplate template = baseMapper.selectOne(new LambdaQueryWrapper<>(SysSmsTemplate.class).eq(SysSmsTemplate::getId, templateId)
            .eq(SysSmsTemplate::getDelFlag, 0));

        if(template == null){
            throw new ServiceException("模板不存在");
        }

        Long channelId = template.getChannelId();
        if(channelId == null){
            throw new ServiceException("渠道不为空");
        }

        SysSmsChannel channel = sysSmsChannelMapper.selectOne(new LambdaQueryWrapper<>(SysSmsChannel.class)
            .eq(SysSmsChannel::getId, channelId)
            .eq(SysSmsChannel::getDelFlag, 0));
        if(channel == null){
            throw new ServiceException("渠道不存在");
        }

        List<SysSmsTemplateParam> paramList = sysSmsTemplateParamMapper.selectList(new LambdaQueryWrapper<>(SysSmsTemplateParam.class)
            .eq(SysSmsTemplateParam::getTemplateId, templateId));

        if(CollectionUtil.isNotEmpty(paramList)){
            Map<String, String> extraParam = dto.getExtraParam();
            if(extraParam.size() == 0){
                throw new ServiceException("缺少必要参数");
            }
            if(paramList.size() != extraParam.size()){
                throw new ServiceException("缺少必要参数");
            }

            Set<String> stringSet = extraParam.keySet();
            for(String str : extraParam.keySet()){
                String values = extraParam.get(str);
                Integer value = Integer.valueOf(values);
                if (values.length() < 4 || values.length() > 6) {
                    // 数字位数不在4到6位之间，抛出错误
                    throw new ServiceException("验证码必须是4到6位");
                }
            }
        }

        Long type = channel.getType();
        MessageService messageService = null;
        Map<String,String> params = dto.getExtraParam() == null ? new LinkedHashMap<>() : dto.getExtraParam();
        SmsParam smsParam = new SmsParam();


        if(type.equals(ChannelTypeEnums.ALIYUN.getTypeCode())){

            BeanUtils.copyProperties(smsConfigProperties,smsParam);
            smsParam.setSignature(channel.getSignature());
            smsParam.setTemplateCode(template.getCode());
            smsParam.setSecretId(channel.getSecretId());
            smsParam.setSecretKey(channel.getSecretKey());
            smsParam.setPhone(dto.getPhone());
//            transformParamMapByList(paramList,params);
            messageService = new AliyunMessageServiceImpl();
            SysSmsLog sysSmsLog = messageService.sendMessage(smsParam, params);
            if(sysSmsLog != null){
                sysSmsLog.setPhone(dto.getPhone());
                sysSmsLog.setTemplateId(templateId);
                sysSmsLog.setContent(getContent(template.getContent(),paramList,dto.getExtraParam()));
                sysSmsLogMapper.insert(sysSmsLog);
            }


        }else if(type.equals(ChannelTypeEnums.TECENTYUN.getTypeCode())){
            messageService = new TencentMessageServiceImpl();
            messageService.sendMessage(smsParam,null);
        }else{
            throw new ServiceException("暂不支持其他类型渠道的短信服务");
        }
    }

    @Override
    public void changeStatus(SysTemplateChangeStatusDTO dto) {
        Long id = dto.getId();
        SysSmsTemplate template = baseMapper.selectOne(new LambdaQueryWrapper<>(SysSmsTemplate.class)
            .eq(SysSmsTemplate::getId, id)
            .eq(SysSmsTemplate::getDelFlag, 0));
        if(template == null){
            throw new ServiceException("模板不存在");
        }
        template.setStatus(dto.getStatus().toString());
        baseMapper.updateById(template);
    }

    /**
     * get content by params
     * */
    private String getContent(String content,List<SysSmsTemplateParam> paramList,Map<String,String> params) {

        if(CollectionUtil.isEmpty(paramList)){
            return content;
        }

//        boolean contentBool = content.("${");
//        if(contentBool){
            for(SysSmsTemplateParam param : paramList) {
                String paramName = param.getParamName();
                String real = "${" + paramName + "}";
                String value = params.get(paramName);
                if (StringUtil.isNotBlank(value)) {
                    String replace = content.replace(real, value);
                    content = replace;
                }
            }
            return content;
//        }else{
//            return content;
//        }
    }
}
